<!--
 * @Description: 你的代码我的心
 * @Author: GGB
 * @Date: 2021-12-21 14:39:03
 * @LastEditors: GGB
 * @LastEditTime: 2022-02-23 13:50:58
-->
<template>
  <div>
    <BasicTable @register="registerTable" @row-click="opDetail">
      <template #action="{ record }">
        <TableAction
          :stopButtonPropagation="true"
          :dropDownActions="[
            {
              label: '详情',
              onClick: opDetail.bind(null, record),
            },
            {
              label: '发货',
              ifShow: showDelivery.bind(null, record),
              onClick: handleExpress.bind(null, record),
            },
            {
              label: '取消订单',
              ifShow: showCancel.bind(null, record),
              popConfirm: {
                title: '是否删取消订单',
                confirm: cancelOrder.bind(null, record),
              },
            },
            {
              label: '确认收货',
              ifShow: showReceipt.bind(null, record),
              popConfirm: {
                title: '是否确定收货',
                confirm: confirmReceipt.bind(null, record),
              },
            },
            {
              label: '确认核销',
              ifShow: showVerify.bind(null, record),
              popConfirm: {
                title: '是否确认核销订单',
                confirm: handleVerify.bind(null, record),
              },
            },
            {
              label: '修改价格',
              ifShow: showUpdatePrice.bind(null, record),
              onClick: updatePrice.bind(null, record),
            },
            {
              label: '审核取消',
              ifShow: showCancelVerify.bind(null, record),
              onClick: VerifyCancel.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
    <DeliveryModal @register="registerDeliveryModal" />
    <UpdatePrice @register="registerUpdateModal" />
    <CancelModal @register="registerCanelModal" />
  </div>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, TableAction, FetchSetting } from '/@/components/Table';
  // schama
  import { columns, searchFormSchema } from './order.data';

  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useGo } from '/@/hooks/web/usePage';
  import { computed, createVNode } from 'vue';
  import { inArray } from '/@/utils';
  import {
    DeliveryStatusEnum,
    DeliveryTypeEnum,
    OrderStatusEnum,
    PayStatusEnum,
  } from '/@/common/enum/order';
  import { OrderRecordModel } from '../model';
  import {
    ApplyCancelType,
    DeliveryType,
    OrderVerifyType,
    ReceiptType,
  } from '/@/api/order/model/orderModel';
  import { applyCancel, confirmReceiptAction, delivery, orderVerify } from '/@/api/order/event';
  import { getOrderList } from '/@/api/order';
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';

  // 组件
  import { DeliveryModal, UpdatePrice, CancelModal } from '../modal';

  const go = useGo();
  const { createMessage } = useMessage();
  const [registerDeliveryModal, deliveryModal] = useModal();
  const [registerUpdateModal, updatePriceModal] = useModal();
  const [registerCanelModal, confirmCancelModal] = useModal();

  const [registerTable, { reload, setLoading }] = useTable({
    title: '订单列表',
    api: getOrderList,
    fetchSetting: {
      sizeField: 'pageSize',
      // // 请求接口当前页数
      pageField: 'page',
      // 请求结果列表字段  支持 a.b.c
      listField: 'list.data',
      // 请求结果总数字段  支持 a.b.c
      totalField: 'list.total',
    } as FetchSetting,
    columns,
    formConfig: {
      labelWidth: 70,
      schemas: searchFormSchema,
      alwaysShowLines: 0,
    },
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    showIndexColumn: false,
    actionColumn: {
      width: 80,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: undefined,
    },
  });

  // 进入订单详情
  const opDetail = (record) => {
    go(`/order/detail/${record.order_id}`);
  };

  // 是否展示发货按钮
  const showDelivery = computed(() => {
    return (item) =>
      item.pay_status == PayStatusEnum['SUCCESS'].value &&
      item.delivery_type !== DeliveryTypeEnum['PICKUP'].value &&
      item.delivery_status == DeliveryStatusEnum['NOT_DELIVERED'].value &&
      !inArray(item.order_status, [
        OrderStatusEnum['CANCELLED'].value,
        OrderStatusEnum['APPLY_CANCEL'].value,
      ]);
  });

  // 订单发货
  const handleExpress = (record: Recordable) => {
    if (record.delivery_type === DeliveryTypeEnum['EXPRESS'].value) {
      deliveryModal.openModal(true, { reload, record: record as OrderRecordModel });
    } else {
      Modal.confirm({
        title: () => '是否发起配送',
        icon: () => createVNode(ExclamationCircleOutlined),
        content: () => createVNode('div', { style: 'color:red;' }, '是否发起配送'),
        onOk: () => {
          setLoading(true);
          let param = { orderId: record.order_id } as DeliveryType;
          delivery(param)
            .then(() => {
              createMessage.success('修改成功');
              reload();
            })
            .catch(() => {
              createMessage.error('修改失败');
            })
            .finally(() => {
              setLoading(false);
            });
        },
      });
    }
  };

  // 是否展示取消订单
  //  还需要包括一种状态--未发起配送
  const showCancel = computed(() => {
    return (item) =>
      item.pay_status == PayStatusEnum['SUCCESS'].value &&
      item.delivery_status == DeliveryStatusEnum['NOT_DELIVERED'].value &&
      !inArray(item.order_status, [
        OrderStatusEnum['CANCELLED'].value,
        OrderStatusEnum['COMPLETED'].value,
      ]);
  });

  // 取消订单
  const cancelOrder = (record: Recordable) => {
    setLoading(true);
    applyCancel({ orderId: record.order_id } as ApplyCancelType)
      .then((res) => {
        createMessage.success(res.message);
        reload();
      })
      .finally(() => setLoading(false));
  };

  // 是否展示确认收货
  const showReceipt = computed(() => {
    return (item) =>
      item.pay_status == PayStatusEnum['SUCCESS'].value &&
      item.order_status == OrderStatusEnum['COMPLETED'].value &&
      !inArray(item.order_status, [
        OrderStatusEnum['CANCELLED'].value,
        OrderStatusEnum['COMPLETED'].value,
      ]);
  });

  // 订单确认收货
  const confirmReceipt = (record: Recordable) => {
    setLoading(true);
    confirmReceiptAction({ orderId: record.order_id } as ReceiptType)
      .then((res) => {
        createMessage.success(res.message);
        reload();
      })
      .finally(() => setLoading(false));
  };
  // 是否展示核销按钮
  const showVerify = computed(() => {
    return (item) =>
      item.pay_status == PayStatusEnum['SUCCESS'].value &&
      item.delivery_type == DeliveryTypeEnum['PICKUP'].value &&
      item.delivery_status == DeliveryStatusEnum['NOT_DELIVERED'].value &&
      !inArray(item.order_status, [
        OrderStatusEnum['CANCELLED'].value,
        OrderStatusEnum['APPLY_CANCEL'].value,
      ]);
  });
  // 订单销核
  const handleVerify = (record: Recordable) => {
    setLoading(true);
    orderVerify({ orderId: record.order_id } as OrderVerifyType)
      .then((res) => {
        createMessage.success(res.message);
        reload();
      })
      .finally(() => setLoading(false));
  };

  // 是否展示修改价格
  const showUpdatePrice = computed(() => {
    return (item) =>
      item.pay_status == PayStatusEnum['PENDING'].value &&
      item.delivery_status == DeliveryStatusEnum['NOT_DELIVERED'].value &&
      !inArray(item.order_status, [
        OrderStatusEnum['CANCELLED'].value,
        OrderStatusEnum['APPLY_CANCEL'].value,
      ]);
  });

  // 修改价格
  const updatePrice = (record: Recordable) => {
    updatePriceModal.openModal(true, { reload, record: record as OrderRecordModel });
  };
  // 是否展示审核取消
  const showCancelVerify = computed(() => {
    return (item) => item.order_status == OrderStatusEnum['APPLY_CANCEL'].value;
  });

  // 审核取消订单
  const VerifyCancel = (record: Recordable) => {
    confirmCancelModal.openModal(true, { reload, record: record as OrderRecordModel });
  };
</script>
